<?php
session_start();

if(!isset($_SESSION['babili']['gid']) || $_SESSION['babili']['gid']!=3 ) die("You are not authorized to access!");

require_once "../../includes/configure.php";

//Connexion a la base de donnees
$connect = mysql_connect(DB_SERVEUR,DB_USER,DB_PASS);

if(isset($_POST['export_utf8']) && $_POST['export_utf8']=="on" ){
	@mysql_query("SET NAMES 'utf8'");
	@mysql_query("SET CHARACTER SET utf8");
}
mysql_select_db(DB_BDD) or die("erreur de connexion a la base de donnees");

/**
 * echo array
 *
 * @param array data
 * @param var data
 * @return void
 */
function echo_pre($data){
	echo "<pre>";
	print_r ($data);
	echo "</pre>";
}

function decode_ent($string){
	return str_replace('&#x','\\u',trim($string) );
}


function convert_charset($item)
{
	if ($unserialize = unserialize($item))
	{
		foreach ($unserialize as $key => $value)
		{
			$unserialize[$key] = @iconv('windows-1256', 'UTF-8', $value);
		}
		$serialize = serialize($unserialize);
		return $serialize;
	}
	else
	{
		return @iconv('windows-1256', 'UTF-8', $item);
	}
}

function unicode_to_utf8($arr,$strict=false) {
    if (!is_array($arr)) return '';
    ob_start();

    foreach (array_keys($arr) as $k) {

        # ASCII range (including control chars)
        if ( ($arr[$k] >= 0) && ($arr[$k] <= 0x007f) ) {

            echo chr($arr[$k]);

        # 2 byte sequence
        } else if ($arr[$k] <= 0x07ff) {

            echo chr(0xc0 | ($arr[$k] >> 6));
            echo chr(0x80 | ($arr[$k] & 0x003f));

        # Byte order mark (skip)
        } else if($arr[$k] == 0xFEFF) {

            // nop -- zap the BOM

        # Test for illegal surrogates
        } else if ($arr[$k] >= 0xD800 && $arr[$k] <= 0xDFFF) {

            // found a surrogate
            if($strict){
                trigger_error(
                    'unicode_to_utf8: Illegal surrogate '.
                        'at index: '.$k.', value: '.$arr[$k],
                    E_USER_WARNING
                    );
                return false;
            }

        # 3 byte sequence
        } else if ($arr[$k] <= 0xffff) {

            echo chr(0xe0 | ($arr[$k] >> 12));
            echo chr(0x80 | (($arr[$k] >> 6) & 0x003f));
            echo chr(0x80 | ($arr[$k] & 0x003f));

        # 4 byte sequence
        } else if ($arr[$k] <= 0x10ffff) {

            echo chr(0xf0 | ($arr[$k] >> 18));
            echo chr(0x80 | (($arr[$k] >> 12) & 0x3f));
            echo chr(0x80 | (($arr[$k] >> 6) & 0x3f));
            echo chr(0x80 | ($arr[$k] & 0x3f));

        } elseif($strict) {

            trigger_error(
                'unicode_to_utf8: Codepoint out of Unicode range '.
                    'at index: '.$k.', value: '.$arr[$k],
                E_USER_WARNING
                );

            // out of range
            return false;
        }
    }

    $result = ob_get_contents();
    ob_end_clean();
    return $result;
}



?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- Made By D.Wassim : wdammak@talend.com -->
	<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
	<title>Administration <?=BABILI_COMPANY?> Babili</title>
	<meta name="description" content="With <?=BABILI_COMPANY?> Babili, Community members can translate the user interface of <?=BABILI_COMPANY?>'s products in any language." />
	<link rel="stylesheet" href="css/general.css" type="text/css" />
	<META NAME="Author" CONTENT="Wassim DAMMAK">
</head>
<body>
<?php 
//echo (unicode_to_utf8('0x6574')); 
function html_to_utf8 ($data){
	return preg_replace("/\\&\\#([0-9]{3,10})\\;/e", '_html_to_utf8("\\1")', $data);
}

function _html_to_utf8 ($data){
    if ($data > 127)
        {
        $i = 5;
        while (($i--) > 0)
            {
            if ($data != ($a = $data % ($p = pow(64, $i))))
                {
                $ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p));
                for ($i; $i > 0; $i--)
                    $ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p));
                break;
                }
            }
        }
        else
        $ret = "&#$data;";
    return $ret;
}

//Example:
//echo html_to_utf8("a b &#5237; &#263; &#382; &#12371; &#12395; &#12385; &#12431; ()[]{}!#$?* &lt; &#62;");

?>
<div id="header">
	<?php include("includes/header.php");  ?> 
</div>

<div id="navcol">
	<?php /*require_once("includes/navleft.php");*/ ?>    
</div>

<div id="sidecol">
	<?php /*require_once("includes/navright.php"); */?>
</div>
<input src="img/back.gif" name="back" id="btnBack" value="Back" onclick="location.href='<?php if(isset($_POST['submit'])) echo "index.php"; else echo '../index.php';?>'" type="image" />

<div id="main">
<?php

$list_project="SELECT * FROM projets WHERE status=1";
$result=mysql_query($list_project);
$datas_projets=array();
while ($row = mysql_fetch_assoc($result)) {
	array_push(
		$datas_projets,
		array(
			'id_projet' => $row['id_projet'],
			'name' => $row['name'],
			'projet_code' => $row['projet_code'],
		)
	);
}


$list_lang="SELECT id_lang, name, short_name, export_short_name FROM languages WHERE status=1";
$result=mysql_query($list_lang);
$datas_lang=array();
while ($row = mysql_fetch_assoc($result)) {
	array_push(
		$datas_lang,
		array(
			'id_lang' => $row['id_lang'],
			'name' =>$row['name'],
			'short_name' =>$row['short_name'],
			'export_short_name' =>$row['export_short_name'],
		)
	);
}

$list_releases="SELECT r.*, p.name as name_projet 
				FROM releases r, projets p 
				WHERE r.id_projet=p.id_projet AND r.status=1 
				ORDER BY r.id_release DESC";
$result=mysql_query($list_releases);
$datas_releases=array();
while ($row = mysql_fetch_assoc($result)) {
	array_push(
		$datas_releases,
		array(
			'id_release' => $row['id_release'],
			'name' =>$row['name'],
			'id_projet' => $row['id_projet'],
			'date' => $row['date'],
			'name_projet' => $row['name_projet'],
		)
	);
}

if(isset($_POST['submit'])){
	$nb_occur=3000000;
	$time_start = microtime(true);
	
	set_time_limit(0);

	echo("<br/>Begin Export<br/>");
	
	$id_release=$_POST['id_release'];
	
	//Get Params
	$get_params_releases=mysql_query("SELECT * FROM releases WHERE id_release=$id_release AND status=1");
	$row_params=mysql_fetch_row($get_params_releases);
	$id_projet=$row_params[3];
	$release_name=$row_params[1];
	
	$version="1.0";
	
	if($_POST['id_lang']!="-1"){
		foreach($datas_lang as $ln){
			if($_POST['id_lang']==$ln['id_lang']){
				$datas_lang= array(array('id_lang'=>$_POST['id_lang'],'name'=>$ln['name'],'short_name'=>$ln['short_name'],'export_short_name'=>$ln['export_short_name']));
				break;
			}
		}		
	}	
	
	$project_id=$id_projet;	
	
	$array_projects[0]=array('id_projet'=>$id_projet);
	
	$name_file=$release_name."-".date("Y-m-d-H-i-s");
	
	//if($_SERVER['HTTP_HOST'] == "localhost" ){
		$path_folder="../../tmp/";
		include_once("php-utf8/utf8.inc");
	//}else{
	//	$path_folder= BABILI_TMP_FOLDER;
	//}

	$path_to=$path_folder.$name_file;
	
	if(!is_dir($path_to)){
		umask(0000);
		if (!mkdir($path_to, 0777,1)) {
			echo "error: creation dossier=> $path_to<br />";
		}
	} else{
		$cmd = 'rm -R "'.$path_to.'"';
		//exec($cmd, $output, $return_val);
	}
	
	foreach($array_projects as $projet){
		
		$_POST['id_projet']=$projet['id_projet'];

		foreach($datas_lang as $ln){
	
			$id_lang=$ln['id_lang'];
			
			$select_all_files="
					SELECT f.`path`, f.`name`,
						   k.`key_name`,
						   t.`translation`
					FROM `map_keys_releases` m 					
					JOIN `keys` as k ON k.`id_key`=m.`id_key`
					JOIN `translation` AS t ON t.`id_key`=k.`id_key`
					JOIN `files` as f ON k.`id_file`=f.`id_file`			
					WHERE k.`id_projet`=".$_POST['id_projet']." AND 
						  t.`id_lang`=".$id_lang." AND
						  m.`id_release`=$id_release AND 
						  t.`translation` <> '' AND 
						  t.`id_status`>0 ";
			
			if($_POST['only_validated']=="on")
				$select_all_files.="
						  AND t.`id_status`=2";
			
			$select_all_files.="
						  ORDER BY k.`id_file`, k.`id_key` ASC
					";
						
			$result=mysql_query($select_all_files);
					
			$datas_keys=array();
			while ($row = mysql_fetch_assoc($result)) {
				
				if($ln['short_name']!='US'){
					if(substr($row['name'],-14)=="_en.properties")
						$row['name']=substr($row['name'],0,-14)."_".$ln['export_short_name'].".properties";
					else
						$row['name']=substr($row['name'],0,-11)."_".$ln['export_short_name'].".properties";	
				}else{
					if((	strtoupper(substr($row['name'],-19))=="MESSAGES.PROPERTIES" || 
							strtoupper(substr($row['name'],-17))=="PLUGIN.PROPERTIES"
						)				
					  ){
							$row['name']=substr($row['name'],0,-11)."_en.properties";
					}	
				}	
								
				$tab=explode('\\',$row['path'],2);
				
				
				//TODO Remove Talend Specific Code
				
				if(strlen($tab[0])>2){					
						$row['path']=$tab[0];
					
					if($tab[1]!=""){
						$row['path'].="\\".$tab[1];
					}
				}
				
				if(DIRECTORY_SEPARATOR=="\\")				
					$row['path']=addslashes($row['path']);
				
				array_push(
					$datas_keys,
					array(				
						'path' =>str_replace('\\', DIRECTORY_SEPARATOR, $row['path']),
						'name' => $row['name'],
						'key_name' => $row['key_name'],
						'translation' => decode_ent($row['translation']),
					)
				);
				
			}					
			
			if($_POST['show_keys'] == "on"){
				echo "<p/>&nbsp;<p/>-------------------------------------------------<br/>";
				echo "&nbsp;Keys: <br/>";
				echo "-------------------------------------------------<br/>";
				echo_pre($datas_keys);	
			}	
				
			$current_file="";
			
			$chmod=0777;		
						
			foreach($datas_keys as $key){
				if($current_file=="" || $current_file!=$key['path'].DIRECTORY_SEPARATOR.$key['name']){
					$current_file=$key['path'].DIRECTORY_SEPARATOR.$key['name'];
					if (!is_dir($path_to.DIRECTORY_SEPARATOR.$key['path'])) {
						umask(0000);
						if (!mkdir($path_to.DIRECTORY_SEPARATOR.$key['path'], 0777,1)) {
							echo $path_to.DIRECTORY_SEPARATOR.$key['path'];
							return FALSE;
						}
					}
					$fp=fopen($path_to.DIRECTORY_SEPARATOR.$current_file,'w');
					exec("chmod 0777 ".$path_to.DIRECTORY_SEPARATOR.$current_file);  
				}
				if($_POST['export_utf8'] == "on"){		
				//unicode_encode ('\u0150\u0179', 'ISO-8859-2');
					fputs($fp,$key['key_name']."=". utf8_encode(utf8_decode(preg_replace('/\n(\r)?/', '\\\\n', $key['translation'])),'ISO-8859-2')."\n");
				}else{
					fputs($fp,$key['key_name']."=".preg_replace('/\n(\r)?/', '\\\\n', $key['translation'])."\n");
				}
			}
		}		
	}
	
	/*if($_POST['id_projet']==1){
		$cmd = 'mv "'.$path_to.DIRECTORY_SEPARATOR.'org.talend.designer.components.localprovider.nl" "'.$path_to.DIRECTORY_SEPARATOR.'org.talend.designer.components.localprovider"';
		exec($cmd, $output, $return_val);
	}*/		
	
	//Zip archive
	chdir($path_folder);
	$cmd = 'tar cjf '.$name_file.'.tar.bz2 '.$name_file;
	exec($cmd, $output, $return_val);
		
	/*$filename = $path_to.".zip";
	include('pclzip.lib.php');
	$archive = new PclZip($filename);
	$archive->create($path_to,PCLZIP_OPT_REMOVE_PATH,$path_to);*/
	
	echo "<br />Download archive: <a href=\"../../tmp/$name_file.tar.bz2\">$name_file.tar.bz2</a><br /><br />";
	
	//$cmd = 'php save_file.php name='.$name_file.'.tar.bz2';
	//echo $cmd;
	//exec($cmd, $output, $return_val);
	
	$cmd = 'rm -R "'.$path_to.'"';
	exec($cmd, $output, $return_val);
	
	$time_end = microtime(true);
	$time = $time_end - $time_start;
	//$_SESSION['path']=$_POST['path'];
	$_SESSION['langue']=$_POST['id_lang'];
	$_SESSION['babili']['project']=$project_id;
	
	printf("<p align=\"left\"><span  style=\"font-size:11px;color:#999999;\">Temps d'ex&eacute;cution: %1\$.2f sec.</span></p>",$time);
	
	echo("End Export<br/>");
		
}else{
		
?>
	<p>&nbsp;</p>
	<form method="post" name="start">
		<table cellspacing="4">
		<tr>
			<td>Export to  path:</td>
			<td><?php echo $path_to; ?></td>
		</tr>
		
		<tr>
			<td>Select Release:</td>
			<td><select id="id_release" name="id_release"><?php foreach($datas_releases as $item) echo '<option value="'.$item['id_release'].'">'.$item['name_projet']." - ".$item['name']." - ".$item['date'].'</option>'; ?></select>
			</td>
		</tr>
		
		<tr>
			<td>Select Langue:</td>
			<td><select id="id_lang" name="id_lang"><?php foreach($datas_lang as $item){ echo '<option value="'.$item['id_lang'].'">'.$item['name'].'</option>'; }
					echo '<option value="-1" selected="selected">ALL</option>';
				?></select>
			</td>
		</tr>
		
		<tr>
			<td>Only Validated:</td>
			<td><input type="checkbox" id="only_validated" name="only_validated" /></td>
		</tr>
		
		<tr>
			<td>Show Keys?</td>
			<td><input type="checkbox" name="show_keys" /></td>
		</tr>
		
		<!--<tr>
			<td>UTF8?</td>
			<td><input type="checkbox" name="export_utf8" /></td>
		</tr>-->
		
		<tr>
			<td colspan="2"><input type="submit" name="submit" value="Export" /></td>
		</tr>
	</table>
	</form>
	<p>&nbsp;</p>
<?php } ?>
</div>

<div id="footer">
	<?php require_once("includes/footer.php"); ?>       
</div>
	
</body>
</html>